let process = {
    MProcedureId: '', parentId: '', detailsNumber: '', procedureId: '', procedureName: '',
    labourHourAmount: '', costPrice: '', subtotal: '', procedureResponsiblePerson: '',
    register: '', registerTime: '', moduleIng: new Array()
}
$(function () {
    $.ajax({
        type: 'POST',
        url: '/userShow.action',
        contentType: 'application/json;charset=utf-8',
        success: function (result) {
            $("#registrant").val(result.loginId)
        }
    })
    $.ajax({
        type: 'POST',
        async: false,
        url: '/zjj/queryProductionDispatchOrdersToBeRegistered.action',
        contentType: 'application/json;charset=utf-8',
        success: function (result) {
            $.each(result.data, function (i, v) {
                let tr = $("<tr></tr>")
                    .append("<td>" + v.manufactureId + "</td>")
                    .append("<td>" + v.productId + "</td>")
                    .append("<td>" + v.productName + "</td>")
                    .append("<td>" + v.amount + "</td>")
                    .append("<td>" + v.registerTime + "</td>")
                    .append("<td><button value='" + v.manufactureId + "' data-toggle=\"modal\" data-target=\"#myModal\" class='btn btn-info' onclick='registerProductionDispatch(this)'>登记</button></td>");
                $("#tbodyCommodity").append(tr);
            })
            jQuery.getScript("../js/datatables.init.js")
        }
    })
})
let arrList;
registerProductionDispatch = e => {
    $.ajax({
        type: 'POST',
        async: false,
        url: '/zjj/queryPendingProductionDispatchOrders.action',
        contentType: 'application/json;charset=utf-8',
        data: $(e).val(),
        success: function (result) {
            $("#tbody").html('')
            arrList = result.data;
            process.parentId = arrList.id
            $("#workOrderNumber").val(arrList.manufactureId)
            $("#productNumber").val(arrList.productId)
            $("#productName").val(arrList.productName)
            $("#description").val(arrList.productDescribe)
            $("#quantity").val(arrList.amount)
            $("#totalCostOfDesignManHours").val(arrList.labourCostPriceSum)
            $("#totalDesignMaterialCost").val(arrList.moduleCostPriceSum)
            $("#actualTotalCostOfLabor").val(arrList.realLabourCostPriceSum == undefined ? '0' : arrList.realLabourCostPriceSum)
            $("#actualTotalMaterialCost").val(arrList.realModuleCostPriceSum == undefined ? '0' : arrList.realModuleCostPriceSum)
            $("#registerPerson").val(arrList.register)
            $("#checkInTime").val(arrList.registerTime)
            $("#reviewer").val(arrList.checker)
            $("#reviewTime").val(arrList.checkTime)
            $("#auditOpinion").val(arrList.remark)
            $.each(arrList.productionProcesses, function (i, v) {
                let tr = $(`<tr>
                    <td>${v.procedureName}</td>
                    <td>${v.labourHourAmount}</td>
                    <td>${v.realLabourHourAmount == undefined ? '0' : v.realLabourHourAmount}</td>
                    <td>${v.subtotal}</td>
                    <td>${v.realSubtotal == undefined ? '0' : v.realSubtotal}</td>
                    <td>${v.moduleSubtotal}</td>
                    <td>${v.realModuleSubtotal == undefined ? '0' : v.realModuleSubtotal}</td>
                    <td class=\"currentProductionOperationStatus\">${checkTheCurrentOperationStatus(v.procedureFinishTag, v.id)}</td>
                    <td>${checkHandoverStatus(v.procedureTransferTag, v.id)}</td>
                    <td style="display: none">${v.id}</td>
                    <td style="display: none">${v.realAmount}</td>
                        </tr>`)
                $("#tbody").append(tr)
                checkTheCurrentOperationStatus(v.id)

            })
        }
    })
}

function checkTheCurrentOperationStatus(e, val) {
    if (e == 'G004-0' || e == 'G004-2') {
        return `<button value="${val}" data-toggle='modal' onclick="checkWhetherThePreviousProcessHasBeenCompleted(this,${val})" class='btn btn-info'>登记</button>`
    } else if (e == 'G004-3') {
        return '已完成'
    } else if (e == 'G004-1') {
        return '等待复核'
    }
}

function checkHandoverStatus(e, val) {
    if (e == 'G005-0') {
        return `<button value="${val}" data-toggle='modal' onclick="handoverProcedure(this,${val})" class='btn btn-info'>交接</button>`
    } else if (e == 'G005-1') {
        return '交接待审核'
    } else if (e == 'G005-2') {
        return '已完成'
    } else {
        return '';
    }
}

function handoverProcedure(e, b) {
    $("#handover").val(b)
    $("#myModal2").modal("show");
}

$("#qualifiedQuantity").change(function () {
    if ($(this).val() <= 0 || parseInt($(this).val()) > parseInt($("#quantity").val())) {
        myCommonUtil.message(1, 'success', '不能大于投产数量或不能小于1')
        sleep(500)
        $(this).val(1)
    }
})
$("#handover").click(function () {
    if (parseInt($("#qualifiedQuantity").val()) <= parseInt($("#quantity").val()) && parseInt($("#qualifiedQuantity").val()) > 0) {
        $("#tbody").children().each(function (i, v) {
            if ($(v).children().eq(9).text() == $("#handover").val()) {
                if ($(v).prev().length == 0 || $("#qualifiedQuantity").val() <= $(v).prev().children().eq(10).text()) {

                    let jsonVal = {
                        id: $("#handover").val(),
                        realAmount: $("#qualifiedQuantity").val()
                    }
                    $.ajax({
                        type: 'POST',
                        async: false,
                        url: '/zjj/submitOperation.action',
                        contentType: 'application/json;charset=utf-8',
                        data: JSON.stringify(jsonVal),
                        success: function (result) {
                            myCommonUtil.message(3);
                            setTimeout(function () {
                                window.location.reload();
                            }, 2000)
                        }
                    })

                } else {
                    myCommonUtil.message(1, 'success', '不能大于上一道工序数量')
                }
            }
        })
    } else {
        myCommonUtil.message(1, 'success', '不能大于投产数量或不能小于1')
    }

})

function checkWhetherThePreviousProcessHasBeenCompleted(e, b) {
    let prev = $(e).parent().parent().prev();
    if ($(prev).length == 0 || ($(prev).children().eq(7).text() == '已完成' && $(prev).children().eq(8).text() == '已完成')) {
        let hoursElapsed = 0;
        $.each(arrList.productionProcesses, function (i, v) {
            hoursElapsed += (v.realLabourHourAmount === undefined ? 0 : v.realLabourHourAmount)
            if (b == v.id) {
                $("#tbBody").html('')
                $("#workOrderNumber1").val($("#workOrderNumber").val())
                $("#processName").val(v.procedureName)
                $("#designWorkingHours").val(v.labourHourAmount)
                $("#hoursElapsed").val(hoursElapsed)
                $("#registrationTime").val(currentTime())
                process.MProcedureId = v.id
                process.detailsNumber = v.detailsNumber
                process.procedureId = v.procedureId
                process.procedureName = v.procedureName
                process.costPrice = v.costPrice
                process.register = $("#registrant").val()
                process.registerTime = $("#registrationTime").val()
                $.each(v.productionMaterial, function (i, v) {
                    let tr = $(`<tr>
                        <td>${v.detailsNumber==undefined?0:v.detailsNumber}</td>  
                        <td>${v.productName}</td>  
                        <td>${v.productId}</td>  
                        <td>${v.amount}</td>  
                        <td>${v.costPrice}</td>  
                        <td><input type="number" onchange="productQuantityChanges(this)" value="0" class="form-control" style="width: 100px;margin: auto"></td>
                            </tr>`)
                    $("#tbBody").append(tr)
                })
                return;
            }
        })
        $("#myModal1").modal(true);
    } else {
        $("#myModal").modal('hide');
        myCommonUtil.message(1, "success", '上一道工序尚未完成或待审核')
    }
}


$("#submitMaterialProduction").click(function () {
    let a = $("#personInCharge").val();
    let b = $("#currentWorkingHours").val();
    if (a != '' && b != '') {
        process.labourHourAmount = $("#currentWorkingHours").val();
        process.subtotal = parseInt(process.labourHourAmount) * parseInt(process.costPrice);
        process.procedureResponsiblePerson = $("#personInCharge").val()
        $("#tbBody").children().each(function (i, v) {
            let MProcedureModuleIng = {
                productId: $(v).children().eq(2).text(),
                detailsNumber: $(v).children().eq(0).text(),
                productName: $(v).children().eq(1).text(),
                costPrice: $(v).children().eq(4).text(),
                amount: $(v).children().eq(5).children().val(),
                subtotal: 0
            }
            MProcedureModuleIng.subtotal = parseInt(MProcedureModuleIng.costPrice) * parseInt(MProcedureModuleIng.amount)
            process.moduleIng.push(MProcedureModuleIng)
        })
        $.ajax({
            type: "post",
            url: "/zjj/submitMaterialProduction.action",
            dataType: "json",
            data: JSON.stringify(process),
            contentType: 'application/json;charset=utf-8',
            success: function (result) {
                if (result.code === 5000) {
                    myCommonUtil.message(1, 'success', result.message)
                } else {
                    myCommonUtil.message(3);
                    setTimeout(function () {
                        window.location.reload();
                    }, 2000)
                }
            }
        })
    } else {
        myCommonUtil.message(1, "success", "请填写负责人或本次工时数");
        return;
    }
})

var myCommonUtil = {
    /**
     * 弹出消息框
     * @param msg 消息内容
     * @param type 消息框类型（参考bootstrap的alert）
     */
    alert: function (msg, type, v) {
        if (typeof (type) == "undefined") { // 未传入type则默认为success类型的消息框
            type = "success";
        }
        // 创建bootstrap的alert元素

        var divElement = $("<div style='width: 320px' class=\"alert alert-light \">\n" +
            "    <svg viewBox=\"0 0 24 24\" width=\"24\" height=\"24\" stroke=\"currentColor\" stroke-width=\"2\" fill=\"none\" stroke-linecap=\"round\" stroke-linejoin=\"round\" class=\"me-2\"><polygon points=\"7.86 2 16.14 2 22 7.86 22 16.14 16.14 22 7.86 22 2 16.14 2 7.86 7.86 2\"></polygon><line x1=\"15\" y1=\"9\" x2=\"9\" y2=\"15\"></line><line x1=\"9\" y1=\"9\" x2=\"15\" y2=\"15\"></line></svg>\n" +
            "    <strong>Error!</strong>" + v + "" +
            "    </button>\n" +
            "</div>")
        let number = parseInt($(window).width()) / 2 - 120;
        let number1 = parseInt($(window).height()) / 2 - 300;
        divElement.css({ // 消息框的定位样式
            "position": "absolute",
            "left": number,
            "z-index": 9999,
            "top": number1
        });
        //divElement.text(msg); // 设置消息框的内容
        // 消息框添加可以关闭按钮
        var closeBtn = $('<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true"><i class="bi bi-x"></i></span></button>');
        $(divElement).append(closeBtn);
        // 消息框放入到页面中
        $('body').append(divElement);
        return divElement;
    },

    success: function () {
        if (typeof (type) == "undefined") { // 未传入type则默认为success类型的消息框
            type = "success";
        }
        var divElement = $("<div class=\"col-xl-3\">\n" +
            "<div class=\"alert alert-success left-icon-big alert-dismissible fade show\">\n" +
            "<div class=\"media\">\n" +
            "<div class=\"alert-left-icon-big\">\n" +
            "    <span><i class=\"mdi mdi-check-circle-outline\"></i></span>\n" +
            "</div>\n" +
            "<div class=\"media-body\">\n" +
            "    <h5 class=\"mt-1 mb-2\">submittedSuccessfully!</h5>\n" +
            "</div>\n" +
            "</div>\n" +
            "</div>\n" +
            "</div>")
        let number = parseInt($(window).width()) / 2 - 120;
        let number1 = parseInt($(window).height()) / 2 - 180;
        divElement.css({ // 消息框的定位样式
            "position": "absolute",
            "left": number,
            "z-index": 9999,
            "top": number1
        });
        //divElement.text(msg); // 设置消息框的内容
        // 消息框添加可以关闭按钮

        // 消息框放入到页面中
        $('body'
        ).append(divElement);
        return divElement;
    },


    /**
     * 短暂显示后上浮消失的消息框
     * @param msg 消息内容
     * @param type 消息框类型
     */
    message: function (msg, type, v) {
        if (msg == 1 || msg == 2) {
            var divElement = myCommonUtil.alert(msg, type, v); // 生成Alert消息框
        } else {
            var divElement = myCommonUtil.success()
        }
        var isIn = false; // 鼠标是否在消息框中

        divElement.on({ // 在setTimeout执行之前先判定鼠标是否在消息框中
            mouseover: function () {
                isIn = true;
            },
            mouseout: function () {
                isIn = false;
            }
        });

        // 短暂延时后上浮消失
        setTimeout(function () {
            var IntervalMS = 20; // 每次上浮的间隔毫秒
            var floatSpace = 60; // 上浮的空间(px)
            var nowTop = divElement.offset().top; // 获取元素当前的top值
            var stopTop = nowTop - floatSpace;    // 上浮停止时的top值
            divElement.fadeOut(IntervalMS * floatSpace); // 设置元素淡出

            var upFloat = setInterval(function () { // 开始上浮
                if (nowTop >= stopTop) { // 判断当前消息框top是否还在可上升的范围内
                    divElement.css({"top": nowTop--}); // 消息框的top上升1px
                } else {
                    clearInterval(upFloat); // 关闭上浮
                    divElement.remove();    // 移除元素
                }
            }, IntervalMS);

            if (isIn) { // 如果鼠标在setTimeout之前已经放在的消息框中，则停止上浮
                clearInterval(upFloat);
                divElement.stop();
            }

            divElement.hover(function () { // 鼠标悬浮时停止上浮和淡出效果，过后恢复
                clearInterval(upFloat);
                divElement.stop();
            }, function () {
                divElement.fadeOut(IntervalMS * (nowTop - stopTop)); // 这里设置元素淡出的时间应该为：间隔毫秒*剩余可以上浮空间
                upFloat = setInterval(function () { // 继续上浮
                    if (nowTop >= stopTop) {
                        divElement.css({"top": nowTop--});
                    } else {
                        clearInterval(upFloat); // 关闭上浮
                        divElement.remove();    // 移除元素
                    }
                }, IntervalMS);
            });
        }, 1500);
    }
}

function currentTime() {
    var now = new Date();
    var year = now.getFullYear();       //年
    var month = now.getMonth() + 1;     //月
    var day = now.getDate();            //日

    var hh = now.getHours();            //时
    var mm = now.getMinutes();          //分

    var clock = year + "-";

    if (month < 10)
        clock += "0";

    clock += month + "-";

    if (day < 10)
        clock += "0";

    clock += day + "T";

    if (hh < 10)
        clock += "0";

    clock += hh + ":";
    if (mm < 10) clock += '0';
    clock += mm;
    return (clock);
}

function productQuantityChanges(e) {
    if ($(e).val() < 0) {
        $(e).val(0)
    }
}